const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const router = new Router()

const views = require('koa-views')
const co = require('co')
const convert = require('koa-convert')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const debug = require('debug')('koa2:server')
const path = require('path')

const config = require('./config')
const routes = require('./routes')
const cors = require('koa-cors')
const cookie = require('koa-cookie')
router.use(cookie.default(``))

const port = process.env.PORT || config.port

// error handler
onerror(app)

// middlewares
app.use(bodyparser())
  .use(json())
  .use(logger())
  .use(require('koa-static')(__dirname + '/public'))
  .use(views(path.join(__dirname, '/views'), {
    options: {settings: {views: path.join(__dirname, 'views')}},
    map: {'njk': 'nunjucks'},
    extension: 'njk'
  }))
  .use(cors())
  .use(router.routes())
  .use(router.allowedMethods())

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - $ms`)
})


//login页面
router.get('/login',async (ctx)=>{
  await ctx.render('login')
})

router.get('/userLogin',(ctx)=>{
  const{name,sex,age} = ctx.request.query;
  let data = {status:true};
  //检测用户名合法
  if(checkName(name)){
    if(checkNameDup(name)){
      data.status =false;
      data.message = '用户名重名'
    }else{
      if(!checkAge(age)){
        data.status =false;
        data.message = '年龄不符'       
      }
    }
  }else{
    data.status =false;
    data.message = '用户名不符合要求'
  }

  ctx.response.body = data;

})



router.get('/checkNameDup', (ctx)=>{
  const {name} = ctx.request.query;
  ctx.response.body = {
    status:checkNameDup(name)
  }
})

function checkNameDup(name){
  const array = ['lily12','bryant65','nancy34','allen01']
  return array.includes(name)
}
function checkName(name){
  const reg = /^[\u4e00-\u9fa5a-zA-Z0-9_-]{4,16}$/
  return reg.test(name)
}
function checkAge(age){
  return age >= 0 && age <=120
}



router.get('/userInfo',async (ctx)=>{
  const {name,age,sex} = ctx.request.query;
  const foods =  [
    { 
      id:1,
      name:'麻辣拌',
      available:true
    },
    { 
      id:2,
      name:'麻辣烫',
      available:false
    },
    { 
      id:3,
      name:'麻辣香锅',
      available:true
    },
    { 
      id:4,
      name:'麻辣鸡爪',
      available:true
    }
  ]
  await ctx.render('userinfo',{
    name,age,sex,foods});
  })


router.get('/content',async (ctx)=>{
  const {keyword} = ctx.request.query;
  const array = ['lucy23','mike15','james47','chris5','tim21'];
  const data = [];
  array.forEach((item)=>{
    if(item.indexOf(keyword) > -1){
      data.push(item)
    }
  })
  ctx.response.body  = data
})



//login2页面
router.get('/login2',async (ctx)=>{
  await ctx.render('login2')
})
//login2下一步页面
router.get('/userLogin2', (ctx)=>{
  const {name} = ctx.request.query;
  console.log(name)
  //到下一步之后 后端向前端颁发cookie
  //然后让前端记住用户名（信息）
  //k-v键值对
  //通过响应头 上的 set-cookie
  //告诉前端 保存什么
  ctx.cookies.set('user',name)
  ctx.response.body = {}
})
//第一次跳转页面main2
router.get('/main2',async,(ctx)=>{
  const user = ctx.cookies.get('user');
  await ctx.render('main')
})




routes(router)
app.on('error', function(err, ctx) {
  console.log(err)
  logger.error('server error', err, ctx)
})

module.exports = app.listen(config.port, () => {
  console.log(`Listening on http://localhost:${config.port}`)
})


